﻿package fab.utils 
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.system.System;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.utils.getTimer ;
	
	public class FPSinfo extends Sprite
	{
		private var _tf : TextField ; 
		
		private var old : Number ; 
		private var cur : Number ; 
		
		private var last : Array ; 
		private var smooth : uint  ;
		public function FPSinfo(autostart : Boolean = true, smooth :uint = 5 ) 
		{
			graphics.beginFill(0, 0.8) ;
			graphics.drawRect(0, 0, 60,45) ; 
			graphics.endFill() ; 
			mouseEnabled = false ;
			mouseChildren = false ;
			
			this.smooth = smooth ; 
			
			_tf = new TextField() ;
			
			var _f : TextFormat = new TextFormat("_sans", 12, 0xFFFFFF, true) ; 
			_tf.setTextFormat(_f);
			_tf.defaultTextFormat = _f ; 
			_tf.multiline = true ; 
			
			addChild(_tf) ; 
			//if ( autostart ) 
			startLog() ;
		}
		
		/**
		 * starts logger
		 */
		public function startLog() : void
		{			
			last = new Array() ; 
			old = getTimer() ; 
			addEventListener(Event.ENTER_FRAME, log) ;
		}
		
		/**
		 * stops logger
		 */
		public function stopLog() : void
		{
			removeEventListener(Event.ENTER_FRAME, log) ;
		}
		
		private function log( e : Event ) : void
		{		
			cur = getTimer() ; 	
			
			var fps : Number = 1000 / ( cur - old ) ;
			last.push(fps) ; 
			if ( last.length > smooth) last.shift() ; 
			
			var j : uint = last.length ; 
			var tot : Number = 0 ;
			while ( --j >= 0 )
			{
				tot += Number(last[j])
			}
			fps = tot / last.length ;
			
			_tf.text = Math.round( fps ) + " FPS\n"  + Number( System.totalMemory / 1024 / 1024 ).toFixed( 2 ) + 'Mb';
			old = cur ;	
			
			
			//trace(cur,Math.round( fps ));
		}
		
	}

}